function getPrevCount(path) {
	var mac = /\.\.\//g;
	var count = 0;
	while (mac.exec(path)) {
		count++
	}
	return count
}
function getRequestUrl(path) {
	if (/http:\/\//g.test(path)) {
		return path
	}
	curWwwPath = window.document.location.href;
	pathName = window.document.location.pathname;
	localhostPaht = curWwwPath.substring(0, curWwwPath.indexOf(pathName));
	filePath = localhostPaht + pathName.substring(0, pathName.substr(1).lastIndexOf('/') + 1);
	prevCount = getPrevCount(path);
	while (prevCount--) {
		filePath = filePath.substring(0, filePath.substr(1).lastIndexOf('/') + 1)
	}
	return filePath + "/" + path.replace(/\.\.\//g, "")
}
function requireFile(path) {
	url = getRequestUrl(path);
	ie = navigator.userAgent.indexOf('MSIE') > 0;
	XHR = ie ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
	try {
		XHR.open('get', url, false);
		XHR.send(null);
		if (XHR.status == 200) {
			return XHR.responseText
		} else {
			console.warn(XHR.status + '-' + path);
		}
	} catch (err) {
		console.warn(err);
	}
}

/*劫持App()函数*/
var module = exports = {};
function App (opts) {
	module.exports = opts
}
function runJs(js) {
	js && window.eval(js);
	return module.exports
}

/*引入js*/
function requireJs(path) {
	js = requireFile('.' + currentDir + path);
	js && window.eval(js);
	return module.exports
}

if(typeof require !== "function") {
	require = requireJs
} else {
	console.warn('环境自带require(), 请修改代码中的require()为requireJs()')
}

/*劫持Page()函数*/
var currentPage, gCss = {};
var Page = function (opts) {
	opts.currentPage = currentPage;
	appData.components || (appData.components = {});
	appData.components[currentPage] = opts
}

var jsDecode = function (key) {
	var js = appData.scripts[key]
	if(!js) {
		console.warn('require(' + key + ')不存在');
		return
	}
	return runJs(js)
}	

/*获取数据*/
var appData;
try {
	appData = baseData
} catch(e) {
	/*本地获取*/
	pathname = window.document.location.pathname;	
	currentDir = '/build' + (pathname != '/' ? pathname : '');
	js = requireFile('.' + currentDir + '/app.js');
	html = requireFile('.' + currentDir + '/app.html');
	json = JSON.parse(requireFile('.' + currentDir + '/app.json'));
	appData = {js, html, json};
	/*注册组件*/
	pages = {};
	tempJS = '';
	for(i in json.components) {
		json.pages.push(json.components[i])
	}
	for (i in json.pages) {
		page = json.pages[i];		
		if(page.indexOf('.') != -1) {
			arr = page.split('.');
			pagePath = arr.join('/');
		} else {
			pagePath = page;
		}
		dir = '.' + currentDir + '/' + pagePath;
		html = requireFile(dir + '.html');
		js = requireFile(dir + '.js') || 'Page({});\n';
		css = requireFile(dir + '.css');

		tempJS += 'currentPage = "'+page+'";\n'+js + ';\n';
		pages[page] = {css, html};
	}
	appData.pages = pages;
	appData.tempJS = tempJS;
}

function copyObjData (data) {
	var _data = {};
	for(i in data) {
		_data[i] = data[i]
	}
	return _data
}

/*注册页面*/	
window.eval(appData.tempJS);
/*创建component*/
function createComponent (key) {
	var opts = appData.components[key];
	if(!opts) {
		return {}
	}
	var components = {};
	/*深度创建组件*/
	for(i in opts.components) {
		k = opts.components[i];
		components[i] = createComponent(k)
	}
	
	return Vue.extend({
		template: appData.pages[opts.currentPage].html,
		props: opts.props || ['data'],
		data: function() {
			return copyObjData(opts.data)
		},
		components,
		beforeCreate: function () {
			/*挂载当前css样式*/	
			gCss[opts.currentPage] = appData.pages[opts.currentPage].css;			
			css = '';
			for(currentCss in gCss) {
				css += gCss[currentCss]
			}
			style = document.getElementById("style");
			style.innerHTML = css
		},
		created: opts.created || function () {},
		beforeMount: opts.beforeMount || function () {},
		mounted: opts.mounted || function () {},
		methods: opts.methods || {},
		watch: opts.watch || {},
		computed: opts.computed || {},
		filters: opts.filters || {},
		directives: opts.directives || {},
		beforeDestroy: opts.beforeDestroy || function () {},

		/*跳转route时清除css*/
		beforeRouteEnter: function (to, from, next) {
			gCss = {};
			next()
		},
		mixins: opts.mixins || []
	})	
}
routes = [];
/*注册全局组件*/
for(i in appData.json.components) {
	Vue.component(i, createComponent(appData.json.components[i]))	
}
/*指定第一个为首页*/
if(appData.json.pages.length > 0) {
	routes.push({
		path: '/',
		redirect: '/' + appData.json.pages[0]
	})
}
for(i in appData.pages) {
	routes.push({
		path: '/' + i,
		component: createComponent(i)
	})
}
/*注册app*/
style = document.createElement("style");
style.setAttribute("id", "style");
document.body.appendChild(style);

div = document.createElement("div");
div.setAttribute("id", "app");
div.innerHTML = appData.html;
document.body.appendChild(div);

opts = appData.js && runJs(appData.js) || {};

components = {};
/*创建组件*/
for(i in opts.components) {
	k = opts.components[i];
	components[i] = createComponent(k);
}

var Vapp = new Vue({
	el: "#app",
	router: new VueRouter({
		routes: self.routes
	}),
	data:copyObjData(opts.data),
	components,
	created: opts.created || function () {},
	mounted: opts.mounted || function () {},
	methods: opts.methods || {},
	watch: opts.watch || {},
	computed: opts.computed || {},
	filters: opts.filters || {},
	directives: opts.directives || {},
	beforeDestroy: opts.beforeDestroy || function () {},
	mixins: opts.mixins || []
})
